package com.shensi.appCollect.utils.tonglianpay.tlfusclasspay;

import com.alibaba.fastjson.JSON;
import com.shensi.api.admin.domian.station.ClassSettlement;
import com.shensi.appCollect.pojo.PayWay;
import com.shensi.appCollect.utils.tonglianpay.SybUtil;
import com.shensi.appCollect.utils.tonglianpay.tlfusclasspay.struct.Request;
import com.shensi.appCollect.utils.tonglianpay.tlfusclasspay.struct.body.TLFusClassPayParam;
import com.shensi.appCollect.utils.tonglianpay.tlfusclasspay.struct.support.ConsumeType;
import com.shensi.appCollect.utils.tonglianpay.tlfusclasspay.struct.support.OilStation;
import com.shensi.appCollect.utils.tonglianpay.tlfusclasspay.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 * 通联退款 分账支付实体类
 */
@Slf4j
public class TLFusClassPayUtil {

    //测试地址
    public static final String TEST_URL = "https://tlgd-test.allinpaygd.com/ug/gateway.do";
    //生产地址
    public static final String PROD_URL = "https://merchant.allinpaygd.com/gateway";
    public static final String DEFAULT_VERSION = "1.0";
    public static final String DEFAULT_SIGN_TYPE = "MD5";
    public static final String DEFAULT_CHARSET = StandardCharsets.UTF_8.toString();

    /**
     * 通联退款 分账支付发送请求
     * @param service
     * @param body
     * @param appId
     * @param appKey
     * @param <T>
     * @return
     * @throws IOException
     */
    private static <T> String post(String service, T body, String appId, String appKey) throws IOException {
        Request<T> request = new Request<>();
        request.setAppId(appId);
        request.setCharset(DEFAULT_CHARSET);
        request.setSignType(DEFAULT_SIGN_TYPE);
        request.setVersion(DEFAULT_VERSION);
        request.setTimestamp(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
        request.setService(service);
        request.setBizContent(body);
        request.sign(appKey);
        String result = HttpUtils.post(PROD_URL, request.toMap());
        request.verify(result, appKey);
        return result;
    }

    /***
     * 通联支付： 业务使用实时班结，与分账支付时调用；
     * @param
     * @return
     * @throws IOException
     */
    public static HashMap tLFusClassPayApply(TLFusClassPayParam pa) throws IOException {
        HashMap resultInfo = new HashMap();
        TLFusClassPayParam payApply = new TLFusClassPayParam();
        payApply.setSysId(pa.getSysId());           //系统ID
        payApply.setAccount(pa.getAccount());       //微信openid，支付宝userId
        payApply.setSubAppId(pa.getSubAppId());     //微信公众号/小程序appid
        payApply.setBizOrderNo(pa.getBizOrderNo()); //订单号
        payApply.setAmount(pa.getAmount());         //金额
        payApply.setBackUrl(pa.getBackUrl());       //回调地址
        payApply.setPayType(pa.getPayType());       //收银宝支付宝（主扫）SCAN_WEIXIN； 收银宝支付宝（主扫）SCAN_ALIPAY；收银宝小程序支付 WECHATPAY_MINIPROGRAM； 收银宝公众号支付：WECHAT_PUBLIC
        //payApply.setLimitPay("no_credit");
        //消费类型
        List<ConsumeType> consumeTypes = new ArrayList<>();
        ConsumeType consumeType = new ConsumeType();
        consumeType.setType(pa.getConsumeType());               //业务类型 C0001 加油； C0002：便利店； C0003：洗车；
        consumeType.setAmount(pa.getAmount());
        consumeTypes.add(consumeType);
        payApply.setConsumeTypes(consumeTypes);

        //油站信息
        OilStation oilStation = new OilStation();
        oilStation.setOilStationNo(pa.getTlOilStationNo());
        payApply.setOilStation(oilStation);

        payApply.setShiftsTime(pa.getShiftsTime());     //班次时间
        payApply.setShiftsMask(pa.getShiftsMask());     //班次标识
        payApply.setRemark(pa.getRemark());


        String post = TLFusClassPayUtil.post("oil.pay.apply", payApply, pa.getTlAppId(), pa.getTlAppKey());
        log.info("通联分账，实时到账预支付接口返回信息：" +post);
        JSONObject jsonObject = JSONObject.fromObject(post);
        if("0000".equals(jsonObject.get("bizCode").toString())){
            if ("WECHATPAY_MINIPROGRAM".equals(pa.getPayType()) || "WECHAT_PUBLIC".equals(pa.getPayType())){
                /**********************微信支付*************************/
                 /*返回参数
                {
                "msg":"SUCCESS",
                "payInterfaceTrxCode":"",
                "finishTime":"",
                "code":"SUCCESS",
                "orderNo":"P20220118000000012424451",
                "payStatusMsg":"进行中",
                "sysId":"1480833167961694210",
                "bizCode":"0000",
                "sign":"56ad0f322a4ab753452d22753522709c",
                "remark":"这是备注",
                "shiftsTime":"20220118",
                "shiftsMask":"2",
                "bizMsg":"处理成功",
                "payInfo":"{\"appId\":\"wxb46701bd193ee573\",
                            \"timeStamp\":\"1642494427\",
                            \"nonceStr\":\"1924ebadd7314805ac762e7c7eeaa530\",
                            \"package\":\"prepay_id=wx18162707708597421cf8564bcf054c0000\",
                            \"signType\":\"RSA\",
                            \"paySign\":\"M5IUB1NrFmcn83vaG8ekvWkmVLFon2ziisM0HXKnT7O/aaeGSAlbYI8VsnUhUgEEl3duncfIqYaA+8m454xjuA0pGHitVPeRNBvoIKR+ojiCJhT2MgfZSgE1x2Js518ZpfLT2Fbthn37Tu8ow48MzpNvy4zytkiof0IzX2bNyi4JTnoZW7aLyW963m2pL+KzLS7ZXGAXU/k8utyTwXZGMGRnNkguE0Jf2ra7GxVVAT4vxmh0GfW3e/Vqq8iL6xIqdMn+bPo6vteWgfjDcs3EKpmlbsEcv7lJN0gClPou3+prEBEf22M2dfKoAz/JgY4THPEQZX2QFxtnc8pl1gX7Lg==\"
                            }",
                "payStatus":"2000",
                "bizOrderNo":"1642494424396"
                }
                * */
                Map payInfoMap = JSON.parseObject(jsonObject.get("payInfo").toString(), Map.class);
                resultInfo.put("payTimeStamp", payInfoMap.get("timeStamp"));
                resultInfo.put("paynonceStr", payInfoMap.get("nonceStr"));
                resultInfo.put("paySignType", payInfoMap.get("signType"));
                resultInfo.put("payPackage", payInfoMap.get("package"));
                resultInfo.put("paySign", payInfoMap.get("paySign"));
                resultInfo.put("payAppId", payInfoMap.get("appId"));
                resultInfo.put("signType", payInfoMap.get("signType"));
            }else {
                /******************支付宝支付************************/
                /*{"msg":"SUCCESS",
                // "payInterfaceTrxCode":"",
                // "finishTime":"","code":"SUCCESS",
                // "orderNo":"P20220128000000012940177",
                // "payStatusMsg":"进行中",
                // "sysId":"1480833167961694210",
                // "bizCode":"0000",
                // "sign":"167cf6a07ffc9d0a5a7f8a641e9ba478",
                // "remark":"-10# - 山东石化367元丰站",
                // "shiftsTime":"20220128",
                // "shiftsMask":"2",
                // "bizMsg":"处理成功",
                // "payInfo":"2022012822001445531422974901",
                // "payStatus":"2000",
                // "bizOrderNo":"1643381270690753191"}*/
                resultInfo.put("source", jsonObject.get("payInfo").toString());
            }
            resultInfo.put("code", jsonObject.get("bizCode"));
            resultInfo.put("msg", jsonObject.get("bizMsg"));
            resultInfo.put("merchantsNumber", jsonObject.get("orderNo"));   //通联单号
            resultInfo.put("ordNo", jsonObject.get("bizOrderNo"));          //商户单号
            resultInfo.put("shiftsTime", jsonObject.get("shiftsTime"));
            resultInfo.put("shiftsMask", jsonObject.get("shiftsMask"));
        }else {
            resultInfo.put("code", jsonObject.get("bizCode"));
            resultInfo.put("msg", jsonObject.get("bizMsg"));
        }
        return resultInfo;
    }
    public static HashMap tLClassSettle(ClassSettlement classSettlement, PayWay payWay) throws Exception {
        HashMap resultInfo = new HashMap();

        TreeMap<String,String> params = new TreeMap<String,String>();
        params.put("appId", payWay.getTlAppId());
        params.put("charset", "utf-8");

        params.put("signtype","MD5");
        params.put("version", "11");
        params.put("timestamp", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        params.put("service", "oil.advance.settle");

        params.put("bizContent", "{\"oilStationNo\":\""+payWay.getTlOilStationNo()+"\",\"shiftsMask\":\""+classSettlement.getTlShiftsMask()+"\",\"shiftsTime\":\""+classSettlement.getTlShiftsTime()+"\",\"sysId\":\""+payWay.getTlSysId()+"\"}");
        params.put("sign", SybUtil.unionSign(params, payWay.getTlAppKey(), "MD5"));



        //params.put("sysId", "1910291133258885426");
        // params.put("cusid", tlPayParam.getCusId());


        //params.put("appKey", "123456");
//        params.put("oilStationNo", "S0015");
//        params.put("班次号", "S0015002");


//        params.put("paytype", tlPayParam.getPayType());
//        params.put("randomstr", SybUtil.getValidatecode(8));
//        params.put("body", tlPayParam.getBody());
//        params.put("remark", tlPayParam.getRemark());
////      params.put("validtime", validtime);
//        params.put("acct", tlPayParam.getAcct());
//        params.put("notify_url", tlPayParam.getNotifyUrl());
////      params.put("limit_pay", limit_pay);
//        params.put("sub_appid", tlPayParam.getSubAppId());
//    params.put("goods_tag", goods_tag);
//    params.put("benefitdetail", benefitdetail);
//    params.put("chnlstoreid", chnlstoreid);
//    params.put("subbranch", subbranch);
//    params.put("extendparams", extendparams);
//    params.put("cusip", cusip);
//    params.put("fqnum", fqnum);
//    params.put("idno", idno);
//    params.put("truename", truename);



        // String appkey = "";
//        switch (tlPayParam.getSIGN_TYPE()){
//            case "RSA":
//                appkey = tlPayParam.getSYB_RSACUSPRIKEY();
//                break;
//            case "SM2":
//                appkey = tlPayParam.getSYB_SM2PPRIVATEKEY();
//                break;
//            case "MD5":
//                appkey = tlPayParam.getSYB_MD5_APPKEY();
//                break;
//        }

        //System.out.println("params:" + params);


        String result = HttpUtils.post("https://cloud.aipgd.com/gateway", params);
//      返回格式：
//        {randomstr=192385841078, cusid=553588055418RR8, appid=00226421,
//        sign=SbLmQ9bqr766wliej9zIvKPu5LmlUuLvVVYHC5sYEON8G+PZ0SKqvga5P12Q+Vsgi59V12yi7fxWcrFXCPlnxwYc+gAyl2Mxa79IUrJmNXgjT0Ri7dM3qynRqLfoCKQhEtwlgzH5uwzd8pk800yqjT6qZ2d3T3knvbXEwVty5yU=,
//        payinfo={
//                "appId": "wx60eecce847c74bcc",
//                "timeStamp": "1639540550",
//                "nonceStr": "557bc5d20695475a99dc935d4a2e023d",
//                "package": "prepay_id=wx15115550909410aa600ce7d5f0a1360000",
//                "signType": "RSA",
//                "paySign": "242DbibuSpyK/YVQflzwNaR6Pg9h2ZkwmNU+JmRzsHC/8D5l2KLcJqg8Ik8Ia6zX7OFg1zUHyn2eHeH8HmC3AvkOnZ1vHTG1CXANF3oSqcvarmmbRh6on9aFzB85cveE1D1lNIF1LJ9Kiy6A+Bijk7GXkYl/b8ZfMZwlpj3F4YRrrZWkroOMDsJepU/CHIJwe3d3j6PbJBIOVSAwvxoLsnaL2lQ2DFWKpDrUQlnWuQPL8wB17oe6QslbC+3hO4T6VYtl/qlgr4NGLrHHgqR4I3aU/sjCB8fzxtP2/jipZsjOx8ILvuxXGxvifil+YIm6KnzvaO8Yetk7JzAM0pM//Q=="
//             }, trxid=211215113309477077, trxstatus=0000, reqsn=1639540552221, retcode=SUCCESS
//        }
        log.info("通联拉起支付返回字段：" +result);
        JSONObject jsonObject = JSONObject.fromObject(result);
        if("0000".equals(jsonObject.get("bizCode"))){

        }else {

        }
        return resultInfo;
    }

}
